import axios from 'axios'

let currentVersion = null

async function fetchVersion() {
  try {
    // Adding a timestamp to prevent caching
    const response = await axios.get(`/version.json?t=${new Date().getTime()}`)
    return response.data.version
  } catch (error) {
    console.error('获取版本文件失败:', error)
    return null
  }
}

export async function checkVersion() {
  if (currentVersion === null) {
    currentVersion = await fetchVersion()
    console.log(`[版本检查] 版本已初始化: ${currentVersion || '获取版本失败'}`)
    // We don't compare on the first check, just initialize.
    return
  }

  const latestVersion = await fetchVersion()

  if (latestVersion) {
    console.log(`[版本检查] 当前版本: ${currentVersion}, 最新版本: ${latestVersion}`)
    if (latestVersion !== currentVersion) {
      console.log('[版本检查] 检测到新版本，正在刷新页面...')
      window.location.reload(true)
    }
  } else {
    console.log('[版本检查] 无法获取最新版本。')
  }
}
